package com.opencms.controller.admin;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.opencms.bean.Module;
import com.opencms.bean.Role;
import com.opencms.bean.SysUser;
import com.opencms.bean.SysUserRole;
import com.opencms.service.ModuleService;
import com.opencms.service.RoleService;
import com.opencms.service.SysUserRoleService;
import com.opencms.service.SysUserService;
import com.opencms.utils.Constants;
import com.opencms.utils.DateUtil;
import com.opencms.utils.ImgCode;
import com.opencms.utils.MD5;
import com.opencms.utils.SessionKey;
import com.opencms.vo.ActionResult;
import com.opencms.vo.Menu;
import com.opencms.vo.QueryResult;

@Controller
@RequestMapping("/admin/")
public class AdminLoginController{
	@Autowired
	private SysUserService sysUserService;
	@Autowired
	private RoleService roleService;
	@Autowired
	private SysUserRoleService sysUserRoleService;
	@Autowired
	private ModuleService  moduleService;
	
	@RequestMapping("loginForm")
	public ModelAndView loginForm(SysUser sysUser,HttpServletRequest request,ModelMap mode) throws Exception{
		ModelAndView mnv = new ModelAndView();
		mnv.setViewName("view/admin/login");
		return mnv;
		
	}
	
	@RequestMapping("login")
	@ResponseBody
	public ActionResult login(SysUser sysUser,HttpServletRequest request,ModelMap mode) throws Exception{
		ActionResult result=new ActionResult();
		QueryResult<SysUser> queryResult=sysUserService.list(sysUser);
		String logincode=request.getParameter("logincode");
		String loginCodeInSession=(String) request.getSession(true).getAttribute("RANDOMVALIDATECODEKEY");
		boolean b=false;
		if(StringUtils.lowerCase(loginCodeInSession).equals(StringUtils.lowerCase(logincode))){
			b=true;
		}
		if(b){
			if(queryResult.getCount()>0){
				SysUser sysUser2=queryResult.getQueryResult().get(0);
				MD5 md5=new MD5();
				if(md5.getMD5ofStr(sysUser.getPassword()).equals(sysUser2.getPassword())){
					sysUser=sysUser2;
					Map<String, Module> modules=new HashMap<String, Module>();
					Map<String, Object> params=new HashMap<>();
					params.put("sysUserId", sysUser.getId());
					List<SysUserRole> sysUserRoles=sysUserRoleService.list(params).getQueryResult();
					for(SysUserRole sysUserRole:sysUserRoles){
						List<Module> modulesList=new ArrayList<Module>();
						Role role=roleService.selectByPrimaryKey(sysUserRole.getRoleId());
						if(role!=null && StringUtils.isNotBlank(role.getModuleIds())){
							params.put("moduleIds", StringUtils.split(role.getModuleIds(),","));
							params.put("orderBy", "order by m.sort desc");
							modulesList=moduleService.list(params).getQueryResult();
						}
						for(Module module:modulesList){
							if(!modules.containsKey(module.getId().toString())){
							    modules.put(module.getId().toString(), module);
							}
						}
					}
					List<Menu> menus=new ArrayList<Menu>();
					for (Entry<String, Module> entry : modules.entrySet()) {
						Module module = entry.getValue();
						if (Constants.MODULU_TYPE_MENU.equals(module.getModuleType()) && module.getpId() == null) {
							Menu menu = new Menu();
							menu.setId(module.getId());
							menu.setName(module.getName());
							menu.setUrl(module.getHref());
							menu.setTarget(module.getTarget());
							menu.setIcon(module.getIcon());
							menus.add(menu);
						}
					}
					request.getSession(true).setAttribute(SessionKey.SYS_USER, sysUser);
					request.getSession(true).setAttribute(SessionKey.SYS_ROLE, sysUserRoles);
					request.getSession(true).setAttribute(SessionKey.SYS_USER_NAME, sysUser.getRealName());
					request.getSession(true).setAttribute(SessionKey.SYS_MODULE, modules);
					request.getSession(true).setAttribute(SessionKey.SYS_MENU, menus);
					sysUser.setLastLoginTime(DateUtil.dateToStr(new Date(), 12));
					sysUserService.saveOrUpdate(sysUser);
					result.setMessage("登录成功");
					result.setSuccess(true);
				}else{
					result.setSuccess(false);
					result.setMessage("密码错误，请输入正确的密码");
				}
			}else{
				result.setSuccess(false);
				result.setMessage("不存在此用户，请检查用户名是否正确");
			}
		}else{
			result.setSuccess(false);
			result.setMessage("验证码输入错误，请重新输入");
		}
		return result;
	}
	
	@RequestMapping("loginOut")
	public String  loginOut(HttpServletRequest request,ModelMap mode) throws Exception{
		request.getSession(true).removeAttribute(SessionKey.SYS_USER);
		request.getSession(true).removeAttribute(SessionKey.SYS_ROLE);
		request.getSession(true).removeAttribute(SessionKey.SYS_USER_NAME);
		request.getSession(true).removeAttribute(SessionKey.SYS_MODULE);
		request.getSession(true).removeAttribute(SessionKey.SYS_MENU);
		return "forward:/admin/loginForm";
		
	}
	
	@RequestMapping("getCode")
	public void  getCode(HttpServletRequest request,HttpServletResponse response,ModelMap mode) throws Exception{
		ImgCode imgCode=new ImgCode();
		imgCode.getRandcode(request,response);
	}

}
